﻿#include "rtfform.h"
#include <QMessageBox>
#include <QDesktopServices>

rtfForm::rtfForm(QString formname, QMap<QString, QString> formdata)
{

    QFile infile(formname);
    if (!infile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QMessageBox::warning(0,"Ошибка","Невозможно открыть "+formname);
        return;
    }
    QFileInfo pathInfo(formname);
    QString ofilename=QDir::tempPath()+"\\res_"+pathInfo.fileName();
    QFile outfile(ofilename);
    if (!outfile.open(QIODevice::WriteOnly | QIODevice::Text|QIODevice::Truncate))
    {
        QMessageBox::warning(0,"Ошибка","Невозможно создать временный файл.");
        return;
    }

    QTextStream in(&infile),out(&outfile);
    QString rtftemplate=in.readAll();

    QMap<QString, QString>::iterator it=formdata.begin();
    for(;it!=formdata.end();++it){
        QString startKey=it.key();
        QString closeKey=it.key();
        closeKey.insert(1,"/");
        QString value=toRtf(it.value());
        QRegExp rx=QRegExp(startKey+"*"+closeKey+"\\par");
        rx.setPatternSyntax(QRegExp::WildcardUnix);
        rx.setMinimal(true);
        if(value.isEmpty()){
            rtftemplate.remove(rx);
            rx.setPattern(startKey+"*"+closeKey);
            rtftemplate.remove(rx);
        }
        else{
        rtftemplate.remove(startKey);
        value.replace("\n","\\par\n");
        rtftemplate.replace(closeKey,value);
        }
    }

    out<<rtftemplate;
    infile.close();
    outfile.close();

    QDesktopServices::openUrl(QUrl("file:///"+ofilename));

}

QString rtfForm::toRtf(QString str)
{
    QString strNew;

    QString latin;
    QString tmp;
    foreach(QChar cr, str)
    {
        if(cr.toLatin1() != QChar(0))
        {
            latin = static_cast<QString>(cr.toLatin1());
            strNew+=latin;
        }
        else
        {
            tmp.setNum(cr.unicode());
            tmp.prepend("\\u");
            tmp.append("?");
            strNew+=tmp;
        }
    }

    return strNew;


}

